package com.rickpan.service.impl;

import com.rickpan.entity.User;
import com.rickpan.enums.Permission;
import com.rickpan.service.PermissionService;
import com.rickpan.service.TeamMemberService;
import com.rickpan.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;

/**
 * 权限服务实现类
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    private static final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TeamMemberService teamMemberService;

    @Override
    public boolean hasPermission(Long userId, Permission permission) {
        try {
            User user = userRepository.findById(userId).orElse(null);
            if (user == null) {
                return false;
            }

            // 管理员拥有所有权限
            if (isAdmin(userId)) {
                return true;
            }

            // 检查VIP权限
            if (permission.isVipPermission() && !isVip(userId)) {
                return false;
            }

            // 检查管理员权限
            if (permission.isAdminPermission() && !isAdmin(userId)) {
                return false;
            }

            // 获取用户默认权限
            Set<Permission> userPermissions = getDefaultPermissions(user.getUserType());
            return userPermissions.contains(permission);

        } catch (Exception e) {
            logger.error("检查用户权限失败 userId={}, permission={}", userId, permission, e);
            return false;
        }
    }

    @Override
    public boolean hasPermissions(Long userId, List<Permission> permissions, boolean requireAll) {
        if (permissions == null || permissions.isEmpty()) {
            return true;
        }

        if (requireAll) {
            // 需要所有权限
            return permissions.stream().allMatch(permission -> hasPermission(userId, permission));
        } else {
            // 需要任一权限
            return permissions.stream().anyMatch(permission -> hasPermission(userId, permission));
        }
    }

    @Override
    public boolean isVip(Long userId) {
        try {
            User user = userRepository.findById(userId).orElse(null);
            if (user == null) {
                return false;
            }

            // 检查用户类型
            if (user.getUserType() != User.UserType.VIP) {
                return false;
            }

            // 检查VIP是否过期
            if (user.getVipExpireTime() != null && user.getVipExpireTime().isBefore(LocalDateTime.now())) {
                return false;
            }

            return true;

        } catch (Exception e) {
            logger.error("检查VIP状态失败 userId={}", userId, e);
            return false;
        }
    }

    @Override
    public boolean isAdmin(Long userId) {
        try {
            User user = userRepository.findById(userId).orElse(null);
            if (user == null) {
                return false;
            }

            return user.getUserType() == User.UserType.ADMIN || user.getRole() == User.Role.ADMIN;

        } catch (Exception e) {
            logger.error("检查管理员状态失败 userId={}", userId, e);
            return false;
        }
    }

    @Override
    public boolean isTeamMember(Long userId, Long teamId) {
        try {
            return teamMemberService.isTeamMember(teamId, userId);
        } catch (Exception e) {
            logger.error("检查团队成员状态失败 userId={}, teamId={}", userId, teamId, e);
            return false;
        }
    }

    @Override
    public boolean isTeamAdmin(Long userId, Long teamId) {
        try {
            return teamMemberService.isTeamAdmin(teamId, userId);
        } catch (Exception e) {
            logger.error("检查团队管理员状态失败 userId={}, teamId={}", userId, teamId, e);
            return false;
        }
    }

    @Override
    public boolean isTeamOwner(Long userId, Long teamId) {
        try {
            return teamMemberService.isTeamOwner(teamId, userId);
        } catch (Exception e) {
            logger.error("检查团队所有者状态失败 userId={}, teamId={}", userId, teamId, e);
            return false;
        }
    }

    @Override
    public Set<Permission> getUserPermissions(Long userId) {
        try {
            User user = userRepository.findById(userId).orElse(null);
            if (user == null) {
                return EnumSet.noneOf(Permission.class);
            }

            Set<Permission> permissions = getDefaultPermissions(user.getUserType());

            // 管理员拥有所有权限
            if (isAdmin(userId)) {
                permissions = EnumSet.allOf(Permission.class);
            }

            return permissions;

        } catch (Exception e) {
            logger.error("获取用户权限失败 userId={}", userId, e);
            return EnumSet.noneOf(Permission.class);
        }
    }

    @Override
    public Set<Permission> getDefaultPermissions(User.UserType userType) {
        Set<Permission> permissions = EnumSet.noneOf(Permission.class);

        switch (userType) {
            case BASIC:
                // 普通用户基础权限
                permissions.addAll(EnumSet.of(
                    Permission.BASIC_USER,
                    Permission.FILE_UPLOAD,
                    Permission.FILE_DOWNLOAD,
                    Permission.FILE_DELETE,
                    Permission.FILE_SHARE,
                    Permission.FILE_PREVIEW,
                    Permission.USER_VIEW,
                    Permission.USER_EDIT,
                    Permission.TEAM_VIEW
                ));
                break;

            case VIP:
                // VIP用户权限（包含普通用户权限 + VIP专属权限）
                permissions.addAll(getDefaultPermissions(User.UserType.BASIC));
                permissions.addAll(EnumSet.of(
                    Permission.TEAM_CREATE,
                    Permission.TEAM_VIEW,
                    Permission.TEAM_MANAGE,
                    Permission.TEAM_INVITE,
                    Permission.TEAM_REMOVE_MEMBER,
                    Permission.PROJECT_CREATE,
                    Permission.PROJECT_MANAGE,
                    Permission.PROJECT_ASSIGN_TASK,
                    Permission.FILE_LARGE_UPLOAD,
                    Permission.FILE_BATCH_OPERATION,
                    Permission.FILE_VERSION_CONTROL,
                    Permission.COLLABORATION_CHAT,
                    Permission.COLLABORATION_DOCUMENT,
                    Permission.COLLABORATION_VIDEO_CALL
                ));
                break;

            case ADMIN:
                // 管理员拥有所有权限
                permissions = EnumSet.allOf(Permission.class);
                break;
        }

        return permissions;
    }

    @Override
    public boolean canOperateTeam(Long userId, Long teamId, Permission permission) {
        // 检查基础权限
        if (!hasPermission(userId, permission)) {
            return false;
        }

        // 检查团队相关权限
        switch (permission) {
            case TEAM_MANAGE:
            case TEAM_DELETE:
                return isTeamAdmin(userId, teamId) || isAdmin(userId);
            case TEAM_INVITE:
            case TEAM_REMOVE_MEMBER:
                return isTeamAdmin(userId, teamId) || isAdmin(userId);
            default:
                return isTeamMember(userId, teamId);
        }
    }

    @Override
    public boolean canOperateProject(Long userId, Long projectId, Permission permission) {
        // TODO: 实现项目权限检查
        // 这里需要根据项目ID查找对应的团队，然后检查团队权限
        return hasPermission(userId, permission);
    }

    @Override
    public boolean canOperateFile(Long userId, Long fileId, Permission permission) {
        // TODO: 实现文件权限检查
        // 这里需要检查文件所有者或团队共享权限
        return hasPermission(userId, permission);
    }
}
